package com.git.utils;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * CSRFTokenManager
 */
public class CSRFTokenUtil {

    public static final String TOKEN_IN_REQUEST = "token";
    public static final String TOKEN_IN_SESSION_NAME = "token_session";

    /**
     * 获取session中的token
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        return (String) request.getSession().getAttribute(TOKEN_IN_SESSION_NAME);
    }
    /**
     * 设置session中的token
     * @param request
     */
    public static void setToken(HttpServletRequest request) {
    	String token = (String) request.getSession().getAttribute(TOKEN_IN_SESSION_NAME);
		if (StringUtils.isBlank(token)) {
			token = UUID.randomUUID().toString();
			request.getSession().setAttribute(TOKEN_IN_SESSION_NAME, token);
		}
    }
    
    /**
     * 刷新session中的token
     * @param request
     */
    public static void refreshToken(HttpServletRequest request) {
		String token = UUID.randomUUID().toString();
		request.getSession().setAttribute(TOKEN_IN_SESSION_NAME, token);
    }
    /**
     * 校验token的正确性
     */
    public static boolean valiToken(HttpServletRequest request){
    	//从request中或者header中取出token
    	String tokenRequest = request.getParameter(TOKEN_IN_REQUEST);
    	if (StringUtils.isBlank(tokenRequest)) {
    		tokenRequest = request.getHeader(TOKEN_IN_REQUEST);
		}
    	
    	//从session中取出token
    	String tokenSession = (String) request.getSession().getAttribute(TOKEN_IN_SESSION_NAME);
    	
    	//返回验证结果
    	return StringUtils.equals(tokenRequest, tokenSession);
    }

}
